//  seconda versione
//  AppDelegate.m
//  primApp
//
//  Created by Giuseppe on 15/11/13.
//
//

#import "AppDelegate.h"
#import "InsertViewController.h"
#import "ListViewController.h"
#import "DetailViewController.h"


@implementation AppDelegate

@synthesize databasePath;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    // Override point for customization after application launch.
    //self.window.backgroundColor = [UIColor colorWithRed:(184/255.0f) green:(24/255.0f) blue:(9/255.0f) alpha:1];
        
    NSMutableArray *controllers = [[NSMutableArray alloc] initWithCapacity:2];
    
    ListViewController *listViewController = [[ListViewController alloc]initWithNibName:nil bundle:nil];
    listViewController.title = @"Lista";
    listViewController.tabBarItem.image = [UIImage imageNamed:@"2.png"];
    
    InsertViewController *insertViewController = [[InsertViewController alloc]initWithNibName:nil bundle:nil];
    insertViewController.title = @"Inserimento";
    insertViewController.tabBarItem.image = [UIImage imageNamed:@"1"];
    [insertViewController setDelegate:listViewController];
    
    UINavigationController *navController = nil;
    navController=[[UINavigationController alloc]initWithRootViewController:listViewController];
    
    //[controllers addObject:listViewController];
    [controllers addObject:navController];
    [controllers addObject:insertViewController];
    
    _tabBarController = [[UITabBarController alloc]init];
    _tabBarController.viewControllers = controllers;
    self.window.rootViewController = _tabBarController;
    
    
    NSLog(@"\nDevice model: %@", [[UIDevice currentDevice] model]);

    
    [self.window makeKeyAndVisible];
    return YES;
}





- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


- (UIImage *)loadImage: (NSString*)filename
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    
    NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",filename] ];
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    
    return image;
}

- (void)saveImage: (UIImage*)image WithName:(NSString*) filename
{
    if (image != nil)
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        
        NSString* path = [documentsDirectory stringByAppendingPathComponent: filename];
        
        NSData* data = UIImagePNGRepresentation(image);
        [data writeToFile:path atomically:YES];
    }
}



#pragma mark - -> Aggiunte: DATABASE utils

/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
 Verifica se il DB esiste nella cartella Documents altrimenti lo copia
 (per avere i permessi in scrittura), crea la tabella ELEMENTS (se non esiste)
 e imposta la variabile databasePath con il path del file myDB.sqlite
 
 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
- (void) initDatabase {
    
    NSString *docsDir;
    NSArray *dirPaths;
    
    // Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docsDir = [dirPaths objectAtIndex:0];
    
    // Build the path to the database file
    databasePath = [[NSString alloc] initWithString:
                    [docsDir stringByAppendingPathComponent:@"myDB.sqlite"]];
    
    NSFileManager *filemgr = [NSFileManager defaultManager];
    
    if ([filemgr fileExistsAtPath: databasePath ] == NO)
    {
        const char *dbpath = [databasePath UTF8String];
        if (sqlite3_open(dbpath, &mySqliteDB) == SQLITE_OK)
        {
            char *errMsg;
            NSString *sql_stmt = @"CREATE TABLE IF NOT EXISTS elements (";
            sql_stmt = [sql_stmt stringByAppendingString:@"id INTEGER PRIMARY KEY AUTOINCREMENT, "];
            sql_stmt = [sql_stmt stringByAppendingString:@"name TEXT, "];
            sql_stmt = [sql_stmt stringByAppendingString:@"origin TEXT, "];
            sql_stmt = [sql_stmt stringByAppendingString:@"description TEXT, "];
            
            sql_stmt = [sql_stmt stringByAppendingString:@"img TEXT, "];
            sql_stmt = [sql_stmt stringByAppendingString:@"tel TEXT, "];
            sql_stmt = [sql_stmt stringByAppendingString:@"data TEXT)"];
            
            if (sqlite3_exec(mySqliteDB, [sql_stmt UTF8String], NULL, NULL, &errMsg) != SQLITE_OK)
            {
                NSLog(@"Failed to create table");
            }
            else
            {
                NSLog(@"ELEMENTS table created successfully");
            }
            
            sqlite3_close(mySqliteDB);
            
        } else {
            NSLog(@"Failed to open/create database");
        }
    } else {
        NSLog(@"OK, il DB esiste");
    }
    
}

/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
 Interroga il DB e ricava la lista di elementi
 
 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
-(NSArray *) getElementsList {
    
    const char *dbpath = [databasePath UTF8String];
    
    NSMutableArray *tmpArray = [[NSMutableArray alloc] init];
    
    if (sqlite3_open(dbpath , &mySqliteDB) == SQLITE_OK) {
        
        const char *sql = "SELECT id,name,origin,description,img,tel,data from ELEMENTS";
        sqlite3_stmt *selectstmt;
        
        if(sqlite3_prepare_v2(mySqliteDB, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
            
            // svuoto prima l'array
            //[_itemList removeAllObjects];
            
            while(sqlite3_step(selectstmt) == SQLITE_ROW) {
                
                int elementID = sqlite3_column_int(selectstmt, 0);
                NSString *name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
                NSString *origin = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
                NSString *description = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)];
                
                NSString *image = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 4)];
                NSString *tel = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 5)];
                NSString *data = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 6)];
                
                Element *myElement = [[ Element alloc]initWithName:name ID:elementID Origin:origin Description:description Image:image Telefono:tel Date:data];
                [tmpArray addObject:myElement];
                
            }
            
            int i=0;
            for(i=0;i<tmpArray.count;i++)
                NSLog(@"tmpArray(%d): %@ - id: %d",i,[[tmpArray objectAtIndex:i] name],[[tmpArray objectAtIndex:i] elementID]);
            
        }
        else NSLog(@"errore lettura DB %s",sqlite3_errmsg(mySqliteDB));
    }
    else sqlite3_close(mySqliteDB);
    
    return tmpArray;
}

/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
 Aggiunge un element nel DB
 
 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
- (BOOL) saveElement:(Element *) myElement
{
    BOOL success = false;
    NSString *insertSQL;
    sqlite3_stmt *statement = NULL;
    const char *dbPath = [databasePath UTF8String];
    
    NSLog(@"save...ID: %d",myElement.elementID);
    
    if (sqlite3_open(dbPath, &mySqliteDB) == SQLITE_OK)
    {
        if (myElement.elementID==0) {
        insertSQL = [NSString stringWithFormat:
                               @"INSERT INTO \"ELEMENTS\" (\"name\",\"origin\",\"description\",\"img\",\"tel\",\"data\") VALUES (\"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\");",
                               myElement.name,
                               myElement.origin,
                               myElement.description,
                               myElement.img,
                               myElement.tel,
                               myElement.date];
        } else {
            
            insertSQL = [NSString stringWithFormat:
                         @"UPDATE \"ELEMENTS\" SET name='%@',origin='%@',description='%@',img='%@',tel='%@',data='%@' WHERE Id=%d",
                         myElement.name,
                         myElement.origin,
                         myElement.description,
                         myElement.img,
                         myElement.tel,
                         myElement.date,
                         myElement.elementID];
        
        }
        
        const char *insert_stmt = [insertSQL UTF8String];
        sqlite3_prepare_v2(mySqliteDB, insert_stmt, -1, &statement, NULL);
        if (sqlite3_step(statement) == SQLITE_DONE)
        {
            success = true;
            
            /*AVSpeechSynthesizer *synthesizer = [[AVSpeechSynthesizer alloc] init];
            AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:[NSString stringWithFormat:@"Bravo! Inserimento di %@ avvenuto correttamente",myElement.name]];
            
            utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"it-IT"];
            utterance.rate = 0.2;
            [synthesizer speakUtterance:utterance];*/
            
            UIAlertView * alertView =
            [[UIAlertView alloc]initWithTitle:@"Bravo"
                                      message:@"Inserimento avvenuto correttamente"
                                     delegate:nil
                            cancelButtonTitle:nil
                            otherButtonTitles:@"Ok", nil];
            [alertView show];
            
        } else
            
            NSLog(@"errore inserimento %s", sqlite3_errmsg(mySqliteDB));
        
        sqlite3_finalize(statement);
        sqlite3_close(mySqliteDB);
        
    }
    
    return success;
}


- (BOOL) deleteElement:(Element *)element
{
    BOOL success = false;
    sqlite3_stmt *statement = NULL;
    const char *dbpath = [databasePath UTF8String];
    
    if (sqlite3_open(dbpath, &mySqliteDB) == SQLITE_OK)
    {
        
        NSLog(@"Delete element %d", element.elementID);
        
        NSString *deleteSQL = [NSString stringWithFormat:@"DELETE from ELEMENTS WHERE id = ?"];
        
        const char *delete_stmt = [deleteSQL UTF8String];
        sqlite3_prepare_v2(mySqliteDB, delete_stmt, -1, &statement, NULL );
        sqlite3_bind_int(statement, 1, element.elementID);
        if (sqlite3_step(statement) == SQLITE_DONE) {
            success = true;
            
        } else
            NSLog(@"errore cancellazione %s",sqlite3_errmsg(mySqliteDB));
        
        sqlite3_finalize(statement);
        sqlite3_close(mySqliteDB);
        
    } else
        
        NSLog(@"errore connessione DB %s",sqlite3_errmsg(mySqliteDB));
    
    return success;
}

@end
